<template>
  <view class="pages">
    <fu-custom bgColor="bg-white" :isBack="true" :isBottom="true">
      <block slot="content">{{i18n['充值']}}</block>
    </fu-custom>
	<view style="margin-top: 30rpx;display: flex;align-items: center;">
		<view style="width: 6rpx;height: 24rpx;background: linear-gradient( 180deg, #FF7EAA 0%, #F63879 100%);margin-right: 30rpx;">
		</view>
		<text style="color: #4D4D4D;">钱包充值</text>
	</view>
	<!-- 固定金额充值 -->
	<view style="display: flex;margin-top: 30rpx;">
		<button @click="changeIndex(index)" :style="{backgroundColor: currentIndex == index?'#FC6397':'#fff',fontSize: '46rpx',color:currentIndex == index?'white':'black'}" v-for="(item,index) in yeList">￥{{item}}</button>
	</view>
	
    <!-- 选择金额 start -->
    <view class="padding bg-white" style="margin-top: 30rpx;">
      <view class="text-bold text-333 fu-fs32" style="font-size: 24rpx;">{{i18n['充值金额']}}</view>
      <view class="flex flex-wrap justify-start recharge-list">
        <view
          class="width-216 height-120 solid recharge-item margin-top-sm flex flex-direction align-center justify-center radius-16"
          :class="act_type == index?'line-theme':''" @click="get_money(item,index)" :data-index="index"
          v-for="(item,index) in moneyData" :key="index">
          <image class="fu-block-30 active" :src="imgBaseUrl + 'wallet/g.png'" mode="" v-if="act_type == index"></image>
          <text class="fu-fs36 ">{{item.add_money}}{{i18n['元']}}</text>
          <!-- <text class="">{{i18n['售价']}} {{item.money}}{{i18n['元']}}</text> -->
        </view>
      </view>
    </view>
    <!-- 选择金额 end -->

    <!-- 充值信息 start -->
    <view class="padding margin-top-sm bg-white">
      <!-- <view class="text-bold text-333 fu-fs32">{{i18n['自定输入金额']}} </view> -->
      <view class="flex align-center margin-top">
        <text class="fu-fs56 text-333 text-bold margin-right-sm">¥</text>
        <input class="text-666 fu-fs40" type="number" placeholder-class="text-bf" @input="handleChange"
          placeholder="0.00" v-model="change_money" />
      </view>
    </view>
    <!-- 充值信息 end -->

    <!-- 充值方式 start -->
    <view class="padding margin-top-sm bg-white">
      <view class="text-bold text-333 fu-fs32" style="font-size: 24rpx;">{{i18n['选择支付方式']}}</view>
      <view class="margin-top-sm solid-top">
        <view class="flex align-center justify-between padding-top" @click="handleSelect(2)">
          <view class="flex align-center">
            <image class="fu-block-56 margin-right-sm" src="@/static/weixin.png" mode=""></image>
            <text>{{i18n['微信']}}</text>
          </view>
          <view>
            <image class="fu-block-36" v-if="acc_type=='2'" :src="imgBaseUrl + 'global/checked.png'" mode="aspectFill">
            </image>
            <image class="fu-block-36" v-else :src="imgBaseUrl + 'global/unchecked.png'" mode="aspectFill"></image>
            <!-- <radio color="#FF5737" :class="acc_type == '1' ? 'checked' : ''" :checked="acc_type == '1' ? true : false" value="1"></radio> -->
          </view>
        </view>
        <!-- #ifndef MP-WEIXIN -->
        <view class="flex align-center justify-between padding-top" @click="handleSelect(1)">
          <view class="flex align-center">
            <image class="fu-block-56 margin-right-sm" :src="imgBaseUrl + 'wallet/zfb.png'" mode=""></image>
            <text>{{i18n['支付宝']}}</text>
          </view>
          <view>
            <image class="fu-block-36" v-if="acc_type=='1'" :src="imgBaseUrl + 'global/checked.png'" mode="aspectFill">
            </image>
            <image class="fu-block-36" v-else :src="imgBaseUrl + 'global/unchecked.png'" mode="aspectFill"></image>
            <!-- <radio color="#FF5737" :class="acc_type == '2' ? 'checked' : ''" :checked="acc_type == '2' ? true : false" value="2"></radio> -->
          </view>
        </view>
        <!-- #endif -->
      </view>
    </view>
    <!-- 充值方式 end -->
    <view class="margin-lr height-88 line-height-88 bg-theme text-white round text-center margin-top-xl" style="background-color: #FE4B88;" @tap="payFn">
      充值
    </view>
    <!-- 断网检测 -->
    <fu-notwork></fu-notwork>
  </view>
</template>

<script>
  /**
   * @author 刘畅
   */
  export default {
    data() {
      return {
        change_money: 100, // {String} 充值金额
        acc_type: 1, // {Number} 充值方式 1:支付宝；2：微信；
        act_type: -1, // {Number} 选择充值的金额
        wxChannel: '', // {String} 获取微信服务供应商
        aliChannel: '', // {String} 获取阿里服务供应商
        moneyData: [], // {Array.<Object>} 选择充值那些金额
        showPopup: false, // {Boolean} 弹窗是否显示
        is_show: true, // {Boolean}
        product_id: 0, // {Number} 选择充值金额的产品id，0：自定义；
        money: '', // {String} 充值金额
		yeList:[
			100,
			200,
			500
		],
		currentIndex:0
      };
    },
    /**
     * @function
     * @description 获取系统信息，获取包支持的服务商信息
     */
    onLoad(options) {
      this.setNavigationBarTitle(this.i18n['充值'])
      let that = this;
      uni.getProvider({
        service: 'payment',
        success: function(res) {
          let provider = res.provider;
          provider.forEach(item => {
            if (item == 'wxpay') {
              that.wxChannel = item;
            } else {
              that.aliChannel = item;
            }
          })
        }
      });
      this.getDetali()
      if (uni.getSystemInfoSync().platform == 'ios') {
        this.is_show = false
      } else {
        this.is_show = true
      }
    },
    onNavigationBarButtonTap(e) {
      this.showPopup = true
    },
    methods: {
		changeIndex(index){
			this.currentIndex = index
			this.change_money = this.yeList[index]
		},
      /**
       * @event
       * @description 切换充值方式
       */
      handleSelect(value) {
        this.acc_type = value
      },
      /**
       * @function
       * @description 获取充值规则
       * @property {Number} group -【规则分组。类型：int(11) unsigned，默认0通用，1 IOS】
       */
      getDetali() {
        this.$api.get(global.apiUrls.getRechargeRule, {
          group: 0,
        }).then(res => {
          console.log(res)
          this.moneyData = res.data.data
        })
      },
      /**
       * @event 手动输入
       * @description 手动输入充值金额
       */
      handleChange() {
        this.act_type = -1;
        this.product_id = 0;
        console.log(this.change_money);
      },
      /**
       * @function
       * @description 支付成功
       * @param {Object} sn - 支付成功
       */
      paySuccess(sn) {
        this.$message.success(this.i18n['支付成功']);
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
        }, 800)

        // if (this.order_type == 12) {
        //   uni.redirectTo({
        //     url: '/pages/integral/integralgoods/exchange-success/index',
        //     order_sn: sn,
        //   })

        // } else {
        //   this.$urouter.redirectTo({
        //     url: '/pages/order/order-process/pay-success/index',
        //     params: {
        //       order_sn: sn,
        //       order_type: 3,
        //       pay_type: this.payType
        //     }
        //   })
        // }
      },
      /**
       * @event
       * @description 点击选择充值金额
       * @param {Obejct} item - 点击的哪一项的详细信息
       * @param {Number} index - 点击的哪一项的序号
       */
      get_money(item, index) {
        this.act_type = index;
        this.change_money = item.money;
        this.money = item.money;
        this.product_id = item.id;
      },
      // get_type(e) {
      //   this.acc_type = e.currentTarget.dataset.index;
      // },
      /**
       * @event
       * @description 点击立即充值按钮
       * @property {Obejct} arr - 请求接口携带的参数
       * @property {Number} arr.order_type - 【订单类型。类型：int(11) unsigned】1 ：'现金充值'，2：'虚拟币充值'，3 ：'商城交易'
       * @property {String} arr.pay_type - 【支付渠道。类型：varchar(256)】wxpay:微信，alipay:支付宝，appleiap:苹果内购
       * @property {String} arr.payable_money - 【应付金额。类型：decimal(10,2)】选填，也可以服务器计算
       * @property {String} arr.order_info - 【商品订单等订单的附加信息。类型：字符串object】
       * @property {String} arr.coupon_id - 【我使用的优惠券id。类型：int(10) unsigned】
       */
      payFn() {
        console.log(this.change_money)
        let {
          acc_type,
          change_money,
          money
        } = this;
        if (this.product_id == 0) {
          if (!change_money) return this.$message.info(this.i18n['请输入充值金额']);
          if (change_money < 1) return this.$message.info(this.i18n['输入金额不能小于1元']);
        }
        let data = {
          order_type: 1,
          pay_type: acc_type == 1 ? 'alipay' : 'wxpay',
          order_money: '',
          product_id: this.product_id,
		  invoice_list:0
        }
        // if (this.is_show) {
        //   // 订单实际付款金额是售价金额
        //   arr.order_money = money;
        // } else {
        //   arr.product_id = this.product_id;
        // }
        // product_id 为0 自定义商品金额
        if (data.product_id != 0) {
          data.order_money = money;
        } else {
          data.order_money = change_money;
        }
        console.log(data);
        this.$api.post(global.apiUrls.postAddOrder, data)
          .then(res => {
            console.log(res);
            if (res.data.code == 1) {
              let sn = res.data.data.order_sn;
              if (this.acc_type == 1) {
                this.$api.post(global.apiUrls.alipayOrder, {
                  order_sn: sn,
                }).then(res => {
                  console.log("支付宝支付回调", res);
                  if (res.data.code == 1) {
                    uni.requestPayment({
                      provider: 'alipay',
                      orderInfo: res.data.data,
                      success: (e) => {
                        if (e.errMsg == 'requestPayment:ok') {
                          this.paySuccess(sn);
                        }
                      },
                      fail: (e) => {
                        if (e.errMsg == 'requestPayment:fail canceled') {
                          this.$message.info(this.i18n['取消支付']);
                        } else {
                          this.$message.info(this.i18n['支付失败,请稍后重试']);
                        }
                      },
                      complete: () => {
                        this.loading = false;
                      }
                    })
                  } else {
                    this.loading = false;
                    this.$message.info(this.i18n["订单无效，支付失败!"]);
                  }
                }).catch(err => {
                  this.loading = false;
                  console.log("支付宝支付失败 => ", err);
                })

              } else {
                this.$api.post(global.apiUrls.wxpayOrder, {
                  order_sn: sn,
                  // #ifdef APP-PLUS
                  wxpaytype: 'apppay',
                  // #endif
                  // #ifdef MP-WEIXIN
                  wxpaytype: 'minipay',
                  // #endif
                }).then(res => {
                  console.log("微信支付回调", res);
                  if (res.data.code == 1) {
                    let data = res.data.data;
                    uni.requestPayment({
                      provider: 'wxpay',
                      // #ifdef MP-WEIXIN
                      timeStamp: data.timeStamp,
                      nonceStr: data.nonceStr,
                      package: data.package,
                      signType: data.signType,
                      paySign: data.paySign,
                      // #endif
                      // #ifdef APP-PLUS
                      orderInfo: data,
                      // #endif
                      success: (e) => {
                        console.log('success', e)
                        if (e.errMsg == 'requestPayment:ok') {
                          this.paySuccess(sn);
                        }
                      },
                      fail: (e) => {
                        console.log('fail', e);
                        // #ifdef APP-PLUS
                        let failMsg = 'requestPayment:fail canceled';
                        // #endif
                        // #ifndef APP-PLUS
                        let failMsg = 'requestPayment:fail cancel';
                        // #endif
                        if (e.errMsg == failMsg) {
                          this.$message.info(this.i18n['取消支付']);
                        } else {
                          this.$message.info(this.i18n['支付失败,请稍后重试']);
                        }

                      },
                      complete: () => {
                        this.loading = false;
                      }
                    });
                  } else {
                    this.loading = false;
                    this.$message.info(this.i18n["订单无效，支付失败!"]);
                  }
                }).catch(err => {
                  this.loading = false;
                  console.error('微信支付失败 =>', err);
                })
              }
            }
          })
          .catch(e => {
            console.log(e)
            this.$message.info(this.i18n["网络繁忙,请稍后重试"]);
          })
      }
    },

  };
</script>

<style lang="scss" scoped>
  .pages {
    .recharge-list {
      .recharge-item {
        margin-right: 20rpx;
        position: relative;

        .active {
          position: absolute;
          top: 0;
          right: 0;
        }

        &:nth-of-type(3n) {
          margin-right: 0;
        }
      }
    }
  }
</style>
